<?php
//打印输出函数
if(!function_exists('dd')){
    function dd(...$args){
        http_response_code(500);
        foreach($args as $x){
            var_dump($x);
        }
        die(1);
    }
}

//当前网站的域名
if(!function_exists('getCurUrl')){
    function getCurUrl(){
        $url = 'http://';
        //判断网络请求协议
        if(isset($_SERVER['SERVER_HTTPS']) && $_SERVER['SERVER_HTTPS'] == 'on'){
            $url = 'https://';
        }
        //判断端口号
        if($_SERVER['SERVER_PORT'] != '80'){
            $url .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'];
        }else{
            $url .= $_SERVER['SERVER_NAME'];
        }
        return $url;
    }
}


//返回数据
if(!function_exists('show')){
    function show(...$params){
        $data = [
            'status' => $params[0],
            'message' => $params[1],
            'data' => $params[2]
        ];
        echo json_encode($data);
    }
}



//判断用户是否登录
if(!function_exists('lh_login')){
    function lh_login($login_type = 'admin'){
        return $_SESSION['admin_token'] == sha1($_SESSION['id'].$_SERVER['HTTP_HOST']) ? 1 : 0;
    }
}

/*
 * 创建文件夹函数
 * $dirPath 当前要上传文件的目录
 * $path 当前要上传文件的完整路径
*/
if(!function_exists('creaDir')){
    function creaDir($dirPath){
        $path = TEMPDIR.'\\'.$dirPath;
        if(is_dir($path) || mkdir($path,0777,true)){
            return $dirPath;
        }
    }
}
/*
 * 上传文件
 * $upFile  当前上传文件的信息
 * 参考文献 https://www.runoob.com/php/php-file-upload.html
 * */
if(!function_exists('uploadToLocal')){
    function uploadToLocal($upFile,$DirName){
       //上传图片的限制
        //允许被上传的图片后缀
        $allowedExts = ["gif","jpeg","jpg","png"];
        $allowedImgTypes = ["image/gif","image/jpeg","image/jpg","image/png","image/pjpeg","image/x-png"];
        $size = 204800;
        $temp = explode(".",$upFile['name']);
        //获取文件后缀
        $extension = end($temp);
        $boolean = in_array($upFile['type'],$allowedImgTypes)
                        && in_array($extension,$allowedExts)
                        && $upFile['size'] < $size
                        && $upFile['error'] == 0
                        && !empty($upFile)
        ;
        if($boolean){
            $dirpath = creaDir('uploads/'.$DirName);
            $filename = $upFile['name'];
            $filename = time().$filename;
            $queryPath = TEMPDIR.'/'.$dirpath.'/'.$filename;
            if(move_uploaded_file($upFile['tmp_name'],$queryPath)){
                return show(1,'success','/'.$dirpath.'/'.$filename);
            }else{
                return show(-1,'error','文件上传失败');
            }
        }else{
            return show(-1,'error',$upFile['error']);
        }
    }
}

